<template>
  <div class="dialog-body">
    <a-form :model="formState" ref="formRef" layout="vertical">
      <a-row :gutter="24">

        <a-col :span="12">
          <a-form-item label="显示名称" name="displayName" :rules="[{ required: true, message: '请输入显示名称' }]">
            <a-input v-model:value="formState.displayName" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="上级菜单" name="parentId">
            <!-- <a-input v-model:value="formState.parentId" /> -->
            <a-tree-select v-model:value="formState.parentId" show-search style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :fieldNames="{label:'displayName',value:'id'}" placeholder="上级菜单" allow-clear
              tree-default-expand-all :tree-data="treeData" tree-node-filter-prop="label">
              <!-- <template #title="{ value: val, label }">
                <b v-if="val === 'parent 1-1'" style="color: #08c">sss</b>
                <template v-else>{{ label }}</template>
              </template> -->
            </a-tree-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="图标">
            <a-select :options="iconOptions" v-model:value="formState.icon">
              <template #option="{ value: val, label }">
                <span class="ai-icon " :class="'ai-icon-' + val"></span>
                &nbsp;&nbsp;{{ label }}
              </template>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="组件">
            <a-input v-model:value="formState.component" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="启用">
            <a-switch v-model:checked="formState.enabled" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="备注">
            <a-input v-model:value="formState.remarks" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item label="地址">
        <a-input v-model:value="formState.url" />
      </a-form-item>
      <a-form-item label="权限">
        <a-row :gutter="20">
          <a-col :span="18">
            <a-input v-model:value="menuPermissionCode" placeholder="菜单权限码">
              <template #addonAfter>
                <a-button type="text" @click="handleGenerate">生成权限码</a-button>
              </template>
            </a-input>
          </a-col>
          <a-col :span="6">
            <a-button type="primary" @click="handleAddPermission">添加</a-button>
          </a-col>
        </a-row>

        <a-table :pagination="false" style="margin-top: 20px;" :dataSource="formState.permissions" :columns="columns">
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.key === 'permissionName'">
              <a-input :disabled="record.isDefault" v-model:value.trim="record.permissionName"></a-input>
            </template>
            <template v-if="column.key === 'permissionCode'">
              <a-input :disabled="record.isDefault" v-model:value.trim="record.permissionCode"></a-input>
            </template>
            <template v-if="column.key === 'isDefault'">
              <a-tag color="green" v-if="record.isDefault">是</a-tag>
              <a-tag color="red" v-if="!record.isDefault">否</a-tag>
            </template>
            <template v-if="column.key === 'action'">
              <a-button type="link" @click="handleDelete(index)">删除</a-button>
            </template>
          </template>
        </a-table>

      </a-form-item>

    </a-form>
  </div>
</template>

<script setup lang="ts">
import { MenuApi } from '@/api/services/index';
import { GetIdInput, MenuDto, QueryApiBaseResultDto, UpdateMenuInput } from '@/api/services/types';
import { FormInstance, message } from 'ant-design-vue';
import { computed, onMounted, ref, watch } from 'vue';
import iconFont from '@/assets/icon-font/iconfont.json'
console.log(iconFont)
const formRef = ref<FormInstance>();

const props = defineProps<{
  id?: string;
}>();
const isEdit = computed(() => {
  if (props.id) {
    return true;
  }
  return false;
})
const formState = ref<UpdateMenuInput>({
  parentId: null,
  displayName: '',
  icon: '',
  url: '',
  component: '',
  remarks: '',
  permissions: [],
  readOnly: false,
  id: '',
  enabled: true
});
const menuPermissionCode = ref<string>('101001')

const iconOptions = computed(() => {
  return iconFont.glyphs.map(x => {
    return {
      value: x.font_class,
      label: x.name
    }
  })
})

const treeData = ref<Array<MenuDto>>([])

const handleGenerate = function () {
  if (!menuPermissionCode.value) {
    message.error('菜单权限码不能为空')
    return;
  }
  if (menuPermissionCode.value.length < 4) {
    message.error('菜单权限码最少4位')
    return;
  }
  if (!formState.value.permissions.find(x => x.isDefault)) {
    formState.value.permissions.push({
      permissionCode: menuPermissionCode.value,
      permissionName: '查看',
      isDefault: true
    })
  }
  let sort = parseInt(menuPermissionCode.value.substring(menuPermissionCode.value.length - 2));
  sort++;
  formState.value.permissions.push({
    permissionCode: menuPermissionCode.value.substring(0, menuPermissionCode.value.length - 2) + sort.toString().padStart(2, '0'),
    permissionName: '导出',
    isDefault: false
  })
  sort++;
  formState.value.permissions.push({
    permissionCode: menuPermissionCode.value.substring(0, menuPermissionCode.value.length - 2) + sort.toString().padStart(2, '0'),
    permissionName: '新增',
    isDefault: false
  })
  sort++;
  formState.value.permissions.push({
    permissionCode: menuPermissionCode.value.substring(0, menuPermissionCode.value.length - 2) + sort.toString().padStart(2, '0'),
    permissionName: '修改',
    isDefault: false
  })
  sort++;
  formState.value.permissions.push({
    permissionCode: menuPermissionCode.value.substring(0, menuPermissionCode.value.length - 2) + sort.toString().padStart(2, '0'),
    permissionName: '删除',
    isDefault: false
  })
}

const handleAddPermission = function () {
  const permissionCode = formState.value.permissions[formState.value.permissions.length - 1].permissionCode;
  let sort = parseInt(permissionCode.substring(permissionCode.length - 2));
  sort++;
  formState.value.permissions.push({
    permissionCode: menuPermissionCode.value.substring(0, menuPermissionCode.value.length - 2) + sort.toString().padStart(2, '0'),
    permissionName: '',
    isDefault: false
  })
}

const handleDelete = function (index: number) {
  formState.value.permissions.splice(index, 1);
}

const loadData = (id: string) => {
  const input: GetIdInput = {
    id: id,
    readOnly: false
  }
  MenuApi.get(input).then(res => {
    const { code, data, msg } = res;
    if (code == 0) {
      formState.value = Object.assign({}, formState.value, data);
    } else {
      message.error(msg)
    }
  })
};

const loadTreeData=function(){
  MenuApi.getAll({}).then(res=>{
    const {code,data,msg} = res;
    if(code==0){
      treeData.value =data.items||[];
    }else{
      message.error(msg)
    }
  })
}

onMounted(()=>{
  loadTreeData();
})

watch(() => props.id, (newId) => {
  if (newId) {
    loadData(newId);
  } else {
    Object.assign(formState, {
      name: '',
      displayName: '',
      contractName: '',
      contractPhone: '',
      enabled: true
    });
  }
}, { immediate: true });

const submit = function (): Promise<QueryApiBaseResultDto<boolean>> {
  return new Promise((resolve, reject) => {
    formRef.value?.validate().then(() => {
      const input = Object.assign(formState.value, { id: props.id })
      const request = isEdit.value ? MenuApi.update(input) : MenuApi.create(input);
      request.then(res => {
        resolve(res);
      }).catch(err => {
        console.error(err)
        reject({
          data: false,
          code: 1,
          msg: '网络错误'
        })
      })
    }).catch((err) => {
      reject({
        data: false,
        code: 2,
        msg: err.errorFields[0].errors[0]
      })
    })
  })


};



const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    width: 70,
    customRender({ index }) {
      return index + 1;
    }
  },
  {
    title: '权限名',
    dataIndex: 'permissionName',
    key: 'permissionName',
  },
  {
    title: '权限码',
    dataIndex: 'permissionCode',
    key: 'permissionCode',
  }
  ,
  {
    title: '是否默认',
    dataIndex: 'isDefault',
    key: 'isDefault',
  }
  ,
  {
    title: '操作',
    dataIndex: 'action',
    key: 'action',
  }
]

defineExpose({
  submit
});
</script>
<style lang="scss" scoped>
.dialog-body {
  height: 600px;
  padding: 20px;
  overflow-y: auto;
}

.c-table {
  width: 100%;
  table-layout: fixed;
  border: none;
  margin: 20px;

  th {
    border: solid 1px #ddd;
    padding: 10px 3px;
  }

  td {
    border: solid 1px #ddd;
    padding: 10px 3px;
  }
}
</style>